package edu.guigu.appquickstart.datastore;

import android.os.Bundle;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.bottomsheet.BottomSheetDialog;

import java.util.ArrayList;

import edu.guigu.appquickstart.R;
import edu.guigu.appquickstart.datastore.adapter.UserBeanAdapter;
import edu.guigu.appquickstart.datastore.bean.UserBean;
import edu.guigu.appquickstart.datastore.dao.DBHelper;
import edu.guigu.appquickstart.datastore.dao.IUserDao;
import edu.guigu.appquickstart.datastore.dao.impl.UserDao;

public class DataStoreActivity extends AppCompatActivity {

    private RecyclerView recyclerView;
    private UserBeanAdapter adapter;
    private ArrayList<UserBean> dataList;
    private IUserDao userDao;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_data_store);
        setSupportActionBar(findViewById(R.id.toolbar));
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        // 适配器
        dataList = new ArrayList<>();
        adapter = new UserBeanAdapter(this, dataList);
        // 列表
        recyclerView = findViewById(R.id.recyclerview);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(adapter);

        // 初始加载数据
        userDao = new UserDao(this);
        dataList.addAll(userDao.getAllUsers());
        adapter.notifyDataSetChanged();

        // 上下文菜单
        registerForContextMenu(recyclerView);

        // 排序
        findViewById(R.id.tv_index).setOnClickListener(sortListener);
        findViewById(R.id.tv_age).setOnClickListener(sortListener);
        findViewById(R.id.tv_name).setOnClickListener(sortListener);
    }

    boolean isAsc = false;
    private View.OnClickListener sortListener = v -> {
        isAsc = !isAsc;
        if (v.getId() == R.id.tv_name) {
            UserBean.userSort(dataList, "name", isAsc);
        }
        if (v.getId() == R.id.tv_index) {
            UserBean.userSort(dataList, "id", isAsc);
        }
        if (v.getId() == R.id.tv_age) {
            UserBean.userSort(dataList, "age", isAsc);
        }
        // 刷新列表
        adapter.notifyDataSetChanged();
    };

    // 上下文菜单----------------------------------------------------------------
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        getMenuInflater().inflate(R.menu.menu_datastore_context, menu);
    }

    @Override
    public boolean onContextItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == R.id.menu_detailed) {
            bottomSheetDialogBox(2);
            return true;
        }
        if (item.getItemId() == R.id.menu_updata) {
            bottomSheetDialogBox(1);
            return true;
        }
        if (item.getItemId() == R.id.menu_delete) {
            // 删除用户
            UserBean userBean = dataList.get(adapter.cLongPosition);
            userDao.deleteUser(userBean.getId());
            // 更新视图
            dataList.remove(userBean);
            adapter.notifyItemRemoved(adapter.cLongPosition);
            return true;
        }
        return super.onContextItemSelected(item);
    }

    /**
     * 0: 添加 ， 1：修改， 2：查看
     */
    private void bottomSheetDialogBox(int mode) {
        BottomSheetDialog bsDialog = new BottomSheetDialog(DataStoreActivity.this);
        // 加载dialog的布局文件,设置到dialog上
        final LayoutInflater layoutInflater = LayoutInflater.from(getApplicationContext());
        View bottomView = layoutInflater.inflate(R.layout.layout_bottomsheet_datastore, null);

        final UserBean userBean = dataList.get(adapter.cLongPosition);
        final EditText et_name = bottomView.findViewById(R.id.et_name);
        final EditText et_age = bottomView.findViewById(R.id.et_age);
        final EditText et_email = bottomView.findViewById(R.id.et_email);
        if (mode == 1 || mode == 2) {
            // TODO： 根据选择的item项，更新显示视图数据
            final TextView tv_id = bottomView.findViewById(R.id.tv_id);
            final TextView tv_register_time = bottomView.findViewById(R.id.tv_register_time);
            tv_id.setText(String.valueOf(userBean.getId()));
            et_name.setText(userBean.getName());
            et_email.setText(userBean.getEmail());
            et_age.setText(String.valueOf(userBean.getAge()));
            tv_register_time.setText(userBean.getRegisterTime());
            if (mode == 2) {
                et_name.setEnabled(false);
                et_age.setEnabled(false);
                et_email.setEnabled(false);
            }
        }

        bsDialog.setContentView(bottomView);
        bsDialog.setCancelable(false);
        bsDialog.show();

        // 拿到dialog上视图上的button，并做监听处理
        bottomView.findViewById(R.id.sure).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 更新用户
                if (mode == 1) {
                    if (userBean != null) {
                        userBean.setName(et_name.getText().toString().trim());
                        userBean.setAge(Integer.parseInt(et_age.getText().toString().trim()));
                        userBean.setEmail(et_email.getText().toString().trim());
                        userDao.updateUser(userBean);
                        adapter.notifyItemChanged(adapter.cLongPosition);
                    }
                }
                // 添加用户
                if (mode == 0) {
                    UserBean newUserBean = new UserBean();
                    newUserBean.setName(et_name.getText().toString().trim());
                    newUserBean.setAge(Integer.parseInt(et_age.getText().toString().trim()));
                    newUserBean.setEmail(et_email.getText().toString().trim());
                    userDao.addUser(newUserBean);
                    dataList.add(newUserBean);
                    adapter.notifyItemInserted(dataList.size());
                }
                bsDialog.dismiss();
            }
        });
    }


    // 选项菜单----------------------------------------------------------------
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_datastore, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
        }
        if (item.getItemId() == R.id.menu_add) {
            bottomSheetDialogBox(0);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 关闭数据库连接
        DBHelper.getInstance(this).closeDB();
    }
}